﻿using CommonServiceLocator;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using RemoteTool.Business.Tools.Helper;
using RemoteTool.Data;
using RemoteTool.Service;
using RemoteTool.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RemoteTool.ViewModel.Controls
{
    public class LoginViewModel : ViewModelBase
    {
        private readonly object operaLocker = new object();

        private string operaMsg;
        public string OperaMsg { get => operaMsg; set { operaMsg = value; RaisePropertyChanged(nameof(OperaMsg)); } }
        public string UserName { get; set; }
        private string _password;
        public string Password { get => _password; set { _password = value; RaisePropertyChanged(nameof(Password)); } }
        /// <summary>
        /// 关闭窗体
        /// </summary>
        public Action CloseAction { get; set; }
        public RelayCommand LoginCmd { get; set; }
        
        public LoginViewModel()
        {
            LoginCmd = new RelayCommand(async () =>await LoginCmdHandlerAsync());
        }

        private async Task LoginCmdHandlerAsync()
        {
            if (Monitor.TryEnter(operaLocker))
            {
                try
                {
                    if (string.IsNullOrEmpty(UserName))
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() => OperaMsg = "用户名不能为空！"); return;
                    }
                    else if (string.IsNullOrEmpty(Password))
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() => OperaMsg = "密码不能为空！"); return;
                    }
                    DispatcherHelper.CheckBeginInvokeOnUI(() => OperaMsg = "正在验证...");
                    var webApiService = ServiceLocator.Current.GetInstance<IWebApiService>();
                    var result = await webApiService.GetAccessTokenAsync(UserName, Password);
                    if (result.success)
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() => CloseAction.Invoke());
                        Messenger.Default.Send<UserInfo>(new UserInfo() { Name = UserName }, MessageToken.ShowUserInfo);
                    }
                    else
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() => OperaMsg = result.message);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("登录异常", ex);
                }
                finally
                {
                    Monitor.Exit(operaLocker);
                }
            }

        }
    }
}
